import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { DataController } from '../controllers/DataController';

export const dataRoutes = new Hono();
const dataController = new DataController();

// 查询参数验证
const querySchema = z.object({
  page: z.string().transform(Number).default('1'),
  limit: z.string().transform(Number).default('20'),
  taskId: z.string().optional(),
  url: z.string().optional(),
  engine: z.enum(['puppeteer', 'playwright', 'http', 'selenium']).optional(),
  isValid: z.string().transform(val => val === 'true').optional(),
  isProcessed: z.string().transform(val => val === 'true').optional(),
  startDate: z.string().optional(),
  endDate: z.string().optional(),
  search: z.string().optional(),
});

const exportSchema = z.object({
  format: z.enum(['json', 'csv', 'xlsx']).default('json'),
  taskId: z.string().optional(),
  startDate: z.string().optional(),
  endDate: z.string().optional(),
});

// 获取爬取数据列表
dataRoutes.get('/', zValidator('query', querySchema), async (c) => {
  try {
    const query = c.req.valid('query');
    const result = await dataController.getData(query);
    return c.json(result);
  } catch (error) {
    console.error('Get data error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch data',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 获取单条数据详情
dataRoutes.get('/:id', async (c) => {
  try {
    const id = c.req.param('id');
    const data = await dataController.getDataById(id);
    
    if (!data) {
      return c.json({
        success: false,
        error: 'Data not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data,
    });
  } catch (error) {
    console.error('Get data by id error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch data',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 删除数据
dataRoutes.delete('/:id', async (c) => {
  try {
    const id = c.req.param('id');
    const success = await dataController.deleteData(id);
    
    if (!success) {
      return c.json({
        success: false,
        error: 'Data not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      message: 'Data deleted successfully',
    });
  } catch (error) {
    console.error('Delete data error:', error);
    return c.json({
      success: false,
      error: 'Failed to delete data',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 批量删除数据
dataRoutes.delete('/', zValidator('json', z.object({
  ids: z.array(z.string()),
})), async (c) => {
  try {
    const { ids } = c.req.valid('json');
    const count = await dataController.bulkDeleteData(ids);
    
    return c.json({
      success: true,
      message: `${count} items deleted successfully`,
      data: { deletedCount: count },
    });
  } catch (error) {
    console.error('Bulk delete data error:', error);
    return c.json({
      success: false,
      error: 'Failed to delete data',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 标记数据为已处理
dataRoutes.post('/:id/processed', async (c) => {
  try {
    const id = c.req.param('id');
    const data = await dataController.markAsProcessed(id);
    
    if (!data) {
      return c.json({
        success: false,
        error: 'Data not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data,
      message: 'Data marked as processed',
    });
  } catch (error) {
    console.error('Mark as processed error:', error);
    return c.json({
      success: false,
      error: 'Failed to mark data as processed',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 标记数据为无效
dataRoutes.post('/:id/invalid', zValidator('json', z.object({
  reason: z.string().optional(),
})), async (c) => {
  try {
    const id = c.req.param('id');
    const { reason } = c.req.valid('json');
    const data = await dataController.markAsInvalid(id, reason);
    
    if (!data) {
      return c.json({
        success: false,
        error: 'Data not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data,
      message: 'Data marked as invalid',
    });
  } catch (error) {
    console.error('Mark as invalid error:', error);
    return c.json({
      success: false,
      error: 'Failed to mark data as invalid',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 导出数据
dataRoutes.get('/export/download', zValidator('query', exportSchema), async (c) => {
  try {
    const query = c.req.valid('query');
    const result = await dataController.exportData(query);
    
    // 设置响应头
    const filename = `crawler-data-${new Date().toISOString().split('T')[0]}.${query.format}`;
    c.header('Content-Disposition', `attachment; filename="${filename}"`);
    
    switch (query.format) {
      case 'csv':
        c.header('Content-Type', 'text/csv');
        break;
      case 'xlsx':
        c.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        break;
      default:
        c.header('Content-Type', 'application/json');
    }
    
    return c.body(result);
  } catch (error) {
    console.error('Export data error:', error);
    return c.json({
      success: false,
      error: 'Failed to export data',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 获取数据统计
dataRoutes.get('/stats/overview', async (c) => {
  try {
    const stats = await dataController.getDataStats();
    return c.json({
      success: true,
      data: stats,
    });
  } catch (error) {
    console.error('Get data stats error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch data statistics',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 获取任务相关数据统计
dataRoutes.get('/stats/by-task/:taskId', async (c) => {
  try {
    const taskId = c.req.param('taskId');
    const stats = await dataController.getTaskDataStats(taskId);
    return c.json({
      success: true,
      data: stats,
    });
  } catch (error) {
    console.error('Get task data stats error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch task data statistics',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 数据去重
dataRoutes.post('/deduplicate', zValidator('json', z.object({
  taskId: z.string().optional(),
  dryRun: z.boolean().default(false),
})), async (c) => {
  try {
    const { taskId, dryRun } = c.req.valid('json');
    const result = await dataController.deduplicateData(taskId, dryRun);
    
    return c.json({
      success: true,
      data: result,
      message: dryRun ? 'Duplicate analysis completed' : 'Data deduplication completed',
    });
  } catch (error) {
    console.error('Deduplicate data error:', error);
    return c.json({
      success: false,
      error: 'Failed to deduplicate data',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});
